package cn.edu.suse.epilepsy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtil {

    private static final long EXPIRE_TIME = 120000*1000;
    // 生成Token
    public static String generateToken(String phone) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String secret = phone.substring(5); // 使用手机号后6位作为密钥
        Algorithm algorithm = Algorithm.HMAC256(secret);

        return JWT.create()
                .withClaim("phone", phone)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    // 获取Token中的指定Claim
    public static String getClaimFromToken(String token, String claimName) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Claim claim = decodedJWT.getClaim(claimName);
            return claim.asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    // 验证Token
    public static boolean verifyToken(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Claim phoneClaim = decodedJWT.getClaim("phone");
            String secret = phoneClaim.asString().substring(5); // 使用手机号后6位作为密钥
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
